﻿///////////////////////////////////////////////////////////////////////////////
//
//  This source is part of the  "Managed Task Framework.NET Runtime"  (MTF.NET Runtime).
//
//
//  Copyright (c) 2011, Multicore Consulting Limited (UK)
//  All rights reserved.
//  http://www.multicoreconsulting.co.uk
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions
//  are met:
//
//  -  Redistributions of source code must retain the above copyright
//     notice, this list of conditions and the following disclaimer.
//  -  Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in
//     the documentation and/or other materials provided with the
//     distribution.
//  -  Neither the name of Multicore Consulting Limited nor the names of
//     its contributors may be used to endorse or promote products
//     derived from this software without specific prior written
//     permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//  POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MTFOrg.MTF.MTFRuntime
{
    /// <summary>
    /// Represents a unit of processing and its relationship with other tasks.
    /// </summary>
    public abstract class Task : ITask
    {
        /// <summary>
        /// Task name
        /// </summary>
        protected string m_Name;

        /// <summary>
        /// Size of each dimension of this task.
        /// </summary>
        protected int[] m_Dimensions;

        /// <summary>
        /// List of sub-tasks owned by this task.
        /// </summary>
        protected List<Task> m_SubTasks;

        /// <summary>
        /// Reference to the task manager used to execute tasks.
        /// </summary>
        protected ITaskManager m_TaskManager;

        /// <summary>
        /// Reference to the parent task of this task.
        /// </summary>
        protected ITask m_ParentTask;

        /// <summary>
        /// List of property names and values associated with this task.
        /// </summary>
        protected Dictionary<string, object> m_Properties;

        /// <summary>
        /// Gets the task name.
        /// </summary>
        public string Name
        {
            get { return m_Name; }
        }

        /// <summary>
        /// Gets the dimensions of this task.
        /// </summary>
        public int[] Dimensions
        {
            get { return m_Dimensions; }
        }

        /// <summary>
        /// Gets the full path from root task to this task.
        /// </summary>
        public string FullPath
        {
            get
            {
                string parentPath = ParentTask != null ? ParentTask.FullPath : string.Empty;
                return parentPath + "/" + Name;
            }
        }

        /// <summary>
        /// Gets the task manager.
        /// </summary>
        public ITaskManager TaskManager
        {
            get { return m_TaskManager; }
        }

        /// <summary>
        /// Gets the parent task of this task.
        /// </summary>
        public ITask ParentTask
        {
            get { return m_ParentTask; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="name">Task name</param>
        /// <param name="dimensions">Task dimensions</param>
        /// <param name="parentTask">Parent task</param>
        /// <param name="taskManager">Task manager</param>
        /// <param name="properties">Properties to apply to the task</param>
        public Task(string name, int[] dimensions, ITask parentTask, ITaskManager taskManager, PropertyGroup properties)
        {
            Create(name, dimensions, parentTask, taskManager, properties);
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="name">Task name</param>
        /// <param name="dimensions">Task dimensions</param>
        /// <param name="parentTask">Parent task</param>
        /// <param name="taskManager">Task manager</param>
        public Task(string name, int[] dimensions, ITask parentTask, ITaskManager taskManager)
        {
            Create(name, dimensions, parentTask, taskManager, null);
        }

        /// <summary>
        /// Creates the task.
        /// </summary>
        /// <param name="name">Task name</param>
        /// <param name="dimensions">Task dimensions</param>
        /// <param name="parentTask">Parent task</param>
        /// <param name="taskManager">Task manager</param>
        /// <param name="properties">Properties to apply to the task</param>
        protected void Create(string name, int[] dimensions, ITask parentTask, ITaskManager taskManager, PropertyGroup properties)
        {
            m_SubTasks = new List<Task>();
            m_ParentTask = parentTask;
            m_Name = name;
            m_Dimensions = dimensions;
            m_TaskManager = taskManager;
            m_Properties = new Dictionary<string, object>();

            if (properties != null)
            {
                foreach (ConnectionProperty property in properties)
                    m_Properties.Add(property.Name, property.Value);
            }
        }

        /// <summary>
        /// Accepts (or rejects) each connection within a set of connections.
        /// </summary>
        /// <param name="newConnections">List of connections to add</param>
        protected void AcceptConnections(MTFRuntime.ConnectionList newConnections)
        {
            // Pass connection list to be filtered
            ConnectionList filteredConnections = TaskManager.FilterConnections(newConnections);

            // Validate connections and link them to their connection points
            foreach (IConnection cxn in filteredConnections)
            {
                IConnectionPoint sourceConnectionPoint = cxn.SourceConnectionPoint;
                IConnectionPoint targetConnectionPoint = cxn.TargetConnectionPoint;

                // Validate the connection prototypes
                if (!TaskManager.CanConnectPoints(sourceConnectionPoint, targetConnectionPoint))
                {
                    throw new IncompatiblePrototypesException("","");
                }

                // Set up in-bound links
                ConnectionList sourceConnections = sourceConnectionPoint.Connections as ConnectionList;
                ConnectionList targetConnections = targetConnectionPoint.Connections as ConnectionList;
                sourceConnections.AddSourceOrdered(new LocatedConnection(cxn, ConnectionType.OwnedConnection));
                targetConnections.AddTargetOrdered(new LocatedConnection(cxn, ConnectionType.RemoteConnection));
            }
        }

        /// <summary>
        /// Processes an incoming event and invokes the appropriate event handler.
        /// </summary>
        /// <param name="eventArgs">Event arguments</param>
        public void ProcessEvent(object eventArgs)
        {
            if (eventArgs is ConnectionFiredEventArgs)
                OnMessage((ConnectionFiredEventArgs)eventArgs);
        }

        /// <summary>
        /// Invoked when a message arrives on any connection.
        /// </summary>
        protected virtual void OnMessage(ConnectionFiredEventArgs cfeArgs)
        {
        }

        /// <summary>
        /// Called to initialize this task.
        /// </summary>
        public virtual void OnInitialize()
        {
            foreach (Task task in m_SubTasks)
                task.OnInitialize();
        }

        /// <summary>
        /// Invoked to request start of application execution.
        /// </summary>
        public virtual void OnBeginExecution()
        {
            ValidateConnections();

            foreach (Task task in m_SubTasks)
                task.OnBeginExecution();
        }

        /// <summary>
        /// Invoked to shut down application.
        /// </summary>
        public virtual void OnEndExecution()
        {
            foreach (Task task in m_SubTasks)
                task.OnEndExecution();
        }

        /// <summary>
        /// Gets the property with the specified name.
        /// </summary>
        /// <param name="name">Name of property to return</param>
        /// <returns>Property object with specified name</returns>
        public object GetProperty(string name)
        {
            return m_Properties.ContainsKey(name) ? m_Properties[name] : null;
        }

        /// <summary>
        /// Called to validate connectivity before commencing execution.
        /// </summary>
        protected virtual void ValidateConnections()
        {
        }

        /// <summary>
        /// Connects this task.
        /// </summary>
        /// <param name="parentTask">Parent task</param>
        /// <returns>null connection list</returns>
        public virtual MTFRuntime.ConnectionList Connect(ITask parentTask)
        {
            return null;
        }

        /// <summary>
        /// Call to start up the top-level task.
        /// </summary>
        public void Startup()
        {
            Connect(null);
            OnInitialize();
            OnBeginExecution();
        }
    }
}
